﻿//===============================================================================
// Apolineo Patterns & Practices LeanEngine Framework
//===============================================================================
// Copyright © Apolineo Desenvolvimento de Sistemas Ltda.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================

using System;
using System.ComponentModel;
using System.Windows.Forms;
using LeanEngine.Entity;
using LeanEngine.Extensions;
using LeanEngine.Collections;
using LeanEngine.SalesConcept.Business;
using LeanEngine.SalesConcept.Entity;

namespace LeanEngine.SalesConcept.Windows.Control
{
    public partial class SearchControlOfSalesman : UserControl
    {
        #region Declaration Members

        [Category("Action")]
        public event Action AddNewSalesman;
        [Category("Action")]
        public event Action<Salesman> UpdateSalesman;
        [Category("Action")]
        public event Action<long> DeleteSalesman;

        private int _selectedRowIndex;

        #endregion

        #region Constructor Members

        public SearchControlOfSalesman()
        {
            InitializeComponent();

            dataGridView1.AutoGenerateColumns = false;
            bindingNavigatorAddNewItem.Enabled = true;
        }

        #endregion

        #region Property Members

        private PagedList<Salesman> CurrentPagedResultList { get; set; }

        [Category("Behavior")]
        [Description("Show or hide the button of add new salesman.")]
        public bool AddNewButtonVisible
        {
            get { return bindingNavigatorAddNewItem.Visible; }
            set { bindingNavigatorAddNewItem.Visible = value; }
        }

        [Category("Behavior")]
        [Description("Show or hide the button of delete the selected salesman.")]
        public bool DeleteButtonVisible
        {
            get { return bindingNavigatorDeleteItem.Visible; }
            set { bindingNavigatorDeleteItem.Visible = value; }
        }

        #endregion

        #region Method Members

        private void UpdateNavigator(int currentPageIndex)
        {
            bindingNavigatorMoveFirstItem.Enabled = (currentPageIndex.IsGreaterThan(0));
            bindingNavigatorMoveLastItem.Enabled = (currentPageIndex.IsLessThan(this.CurrentPagedResultList.PageCount));
            bindingNavigatorMoveNextItem.Enabled = (currentPageIndex.IsLessThan(this.CurrentPagedResultList.PageCount));
            bindingNavigatorMovePreviousItem.Enabled = (currentPageIndex.IsGreaterThan(0));
        }

        private void UpdateBindPage(int pageIndex)
        {
            if (pageIndex.IsLessThan(0)) pageIndex = 0;
            else if (pageIndex.IsGreaterThan(GetMaxPageIndex()) && GetMaxPageIndex().IsGreaterThanEqual(0)) pageIndex = GetMaxPageIndex();

            var criteria = new PersonSearchCriteria()
            {
                PageIndex = pageIndex,
                PageSize = 25,
                Name = this.txtName.Text.Trim(),
                DocumentNumber = this.txtDocumentNumber.Text.Trim()
            };

            this.CurrentPagedResultList = new SaleBusinessFacade(Program.LoginToken).ListSalesmanByPersonCriteria(criteria);

            dataGridView1.DataSource = null;
            dataGridView1.DataSource = this.CurrentPagedResultList.Items;

            bindingNavigator1.PositionItem.Text = (pageIndex + 1).ToString();
            bindingNavigator1.CountItem.Text = "de " + (this.CurrentPagedResultList.PageCount + 1).ToString();
        }

        private int GetMaxPageIndex()
        {
            var pageCount = bindingNavigatorCountItem.Text.Replace("de", string.Empty).Trim();
            return pageCount.ToInt32();
        }

        private int GetCurrentPageIndex()
        {
            return bindingNavigatorPositionItem.Text.IsNumeric() ? bindingNavigatorPositionItem.Text.ToInt32() : 0;
        }

        protected virtual void OnAddNewSalesman()
        {
            if (this.AddNewSalesman.IsNotNull())
            {
                this.AddNewSalesman.Invoke();
            }
        }

        protected virtual void OnUpdateSalesman(Salesman value)
        {
            if (this.UpdateSalesman.IsNotNull())
            {
                this.UpdateSalesman.Invoke(value);
            }
        }

        protected virtual void OnDeleteSalesman(long key)
        {
            if (this.DeleteSalesman.IsNotNull())
            {
                this.DeleteSalesman.Invoke(key);
            }
            else
            {
                new SaleBusinessFacade(Program.LoginToken).DeleteSalesmanById(key);
                var pageIndex = GetCurrentPageIndex();

                if ((this.CurrentPagedResultList.Items.Count - 1).IsLessThan(1))
                {
                    pageIndex -= 1;
                    if (pageIndex.IsLessThan(0)) pageIndex = 0;
                }

                UpdateBindPage(pageIndex);
            }
        }

        #endregion

        #region Event Members

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (this._selectedRowIndex.IsGreaterThanEqual(0) &&
                    this.CurrentPagedResultList.Items.Count.IsGreaterThan(this._selectedRowIndex))
                {
                    var value = this.CurrentPagedResultList.Items[this._selectedRowIndex];
                    OnUpdateSalesman(value);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void bindingNavigatorMoveFirstItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                UpdateBindPage(0);
                UpdateNavigator(0);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void bindingNavigatorMovePreviousItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                var currentPageIndex = GetCurrentPageIndex();
                UpdateBindPage(--currentPageIndex);
                UpdateNavigator(currentPageIndex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                var currentPageIndex = GetCurrentPageIndex();
                UpdateBindPage(++currentPageIndex);
                UpdateNavigator(currentPageIndex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void bindingNavigatorMoveLastItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                UpdateBindPage(GetMaxPageIndex());
                UpdateNavigator(GetMaxPageIndex());
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                OnAddNewSalesman();
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (dataGridView1.SelectedRows.Count > 0)
                {
                    var key = this.CurrentPagedResultList.Items[dataGridView1.SelectedRows[0].Index].Id;
                    OnDeleteSalesman(key);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                UpdateBindPage(0);
                UpdateNavigator(0);
                if (this.CurrentPagedResultList.TotalItems == 0)
                {
                    MessageBox.Show("Nenhum cliente encontrado com os parametros informados.", this.Parent.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            _selectedRowIndex = e.RowIndex;
            bindingNavigatorDeleteItem.Enabled = _selectedRowIndex.IsGreaterThanEqual(0);
        }

        #endregion
    }
}
